package com.leyou.order.scheduler;

import com.leyou.order.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class PayScheduler {
    @Autowired
    private PayService payService;
    @Autowired
    private RedissonClient redissonClient;

   //锁名字
    public static final String LOCK_NAME="LOCK_PAY";
    //    20分钟  _20Minutes
    @Scheduled(fixedDelay = 1000*60*1)
    public void pay_20MinutesExpiration() {
        //创建锁对象
        RLock lock = redissonClient.getLock(LOCK_NAME);

        //获取锁
        boolean tryLock = lock.tryLock();

        //判断
        if (!tryLock){
            log.info("未能获取任务锁,结束任务");
            return;
        }
        try {
            log.info("获取锁成功,执行定时任务");
            //执行任务,获取锁失败,结束任务
            //获取当前系统时间
            DateTime dateTime = DateTime.now();
            //当前系统时间-20分钟(如果小于创建时间,说明还没有过期) 1200秒

            Date date = dateTime.minusSeconds(30).toDate();
            //修改订单状态,库存
            payService.outTimeOreder(date);
            log.info("20分钟订单支付过期");
            //用户下单后,超过2小时未支付成功的订单,状态改为已失效
            //2小时=2*60分钟*60秒
            Date twoHourDate = dateTime.minusSeconds(7200).toDate();
            payService.OutTwoTimeOrder(twoHourDate);
            log.info("2小时订单关闭");
        } catch (Exception e) {
           log.error("任务执行异常",e);
        } finally {
         //释放锁
            lock.unlock();
            log.info("任务执行完毕,释放锁");
        }
    }
}
